#-*- coding:utf-8 -*-
import os
import sys
import shutil
from datetime import datetime as dt
from ShortMessage import alert_module_pyMuPDF
from ShortMessage import MSG,test_file_exists,test_pymupdf_imported,message_finished,message_started
from muSplitPdf import muSplitPdfObject
from muCropPdf import muCropPdfObject
from muInsertPagePdf import muInsertPagePdfObject
from ArgumentParse import getMakePrintablePdfParseResult
from UtilFunction import getPageRange
FITZ_IMPORT_FAIL = False
try:
    import fitz 
except:
    FITZ_IMPORT_FAIL =True
A4_WIDTH_HEIGHT_RATIO = 0.7
def muMakePrintablePdfObject(input_pdf,ride_ratio):
    if type(input_pdf) == type(""):
        input_pdf = fitz.open(input_pdf)
    page_count = input_pdf.pageCount
    #a4纸的宽度选择原书籍宽度
    a4_width = pg_width = input_pdf[0].rect.width
    pg_height = input_pdf[0].rect.height
    a4_height = a4_width/A4_WIDTH_HEIGHT_RATIO
    MSG("Origin Book Page-size    -> width:%.2f, height:%.2f"%(pg_width,pg_height))
    MSG("Set A4 Size              -> width:%.2f, height:%.2f(Use Origin's Width)"%(a4_width,a4_height))

    zoom_height = a4_width
    zoom_width = pg_width**2/pg_height
    MSG("Plan Page-size           -> Width:%.2f, Height:%.2f (ROTATE 90)"%(zoom_width,zoom_height))
    if (zoom_width*2+ride_ratio*a4_height) > a4_height:
        MSG("* Use %.2f (A4-Width/2),For A4-page-hight  Is LESS THAN Two Page Width(%.2f<%.2f*2)"%(a4_height/2,a4_height,zoom_width))
        zoom_width = (a4_height-ride_ratio*a4_height)/2
        zoom_height = pg_height/pg_width*zoom_width#保持原有比例
    MSG("Actual Page Size         -> Width:%.2f, Height:%.2f"%(zoom_width,zoom_height))
    top_rect = fitz.Rect(0,0                       ,a4_width   ,zoom_width)
    but_rect = fitz.Rect(0,a4_height-zoom_width,a4_width,a4_height)
    out_pdf = fitz.Document(rect=fitz.Rect(0,0,a4_width,a4_height),width=a4_width,height=a4_height)
    pg_group_count = int(page_count/4)
    if page_count%4 != 0:
        pg_group_count += 1
    for gp_index in range(pg_group_count):
        for st in (0,1):
            out_page =None
            if (gp_index*4+st)<page_count:
                out_page = out_pdf.newPage(width= a4_width,height=a4_height)  
                try:          
                    out_page.showPDFpage(but_rect,input_pdf,gp_index*4+st,rotate=(st-0.5)*180)
                except ValueError:
                    pass#复制空白页面会报错，但不影响结果
            if (gp_index*4+3-st)<page_count:
                try:
                    out_page.showPDFpage(top_rect,input_pdf,gp_index*4+3-st,rotate=(st-0.5)*180)
                except ValueError:
                    pass#复制空白页面会报错，但不影响结果
    return out_pdf
def muMakePrintablePdfFile(input_pdf,output_pdf_str,ride_ratio):
    output_pdf = muMakePrintablePdfObject(input_pdf,ride_ratio)
    try:
        output_pdf.save(output_pdf_str)
        MSG("Success Make Printable File to [%s]"%output_pdf_str)
    except:
        if os.path.exists(output_pdf_str):
            MSG("Save Fail,Try Close The File!")
        else:
            MSG("Save Fail,Unkown Error!")
    message_finished()
if __name__ == "__main__":
    if test_pymupdf_imported():
        result = getMakePrintablePdfParseResult(sys.argv)
        if test_file_exists(result.input_pdf):
            page_range_list,wholeBook = getPageRange(result.range_list,result.split_list)
            input_pdf = result.input_pdf
            base_output_pdf = ""
            if result.output_pdf:
                base_output_pdf = os.path.join(os.getcwd(),result.output_pdf[:-4])
            else:
                base_output_pdf = input_pdf[:-4]
            if result.margin_ratios:
                input_pdf = muCropPdfObject(input_pdf,result.margin_ratios)
            if  wholeBook:
                output_pdf = "%s_result.pdf"%base_output_pdf
                muMakePrintablePdfFile(input_pdf,output_pdf,ride_ratio=result.ride_ratio)
            else:
                need_fix_cover_index =[]
                if result.fix_cover:
                    need_fix_cover_index = [int(x)-1 for x in result.fix_cover.split(",")]
                for i,pr in enumerate(page_range_list):
                    output_pdf = "%s_%s-%s_result.pdf"%(base_output_pdf,pr[0]+1,pr[1]+1)
                    tmp_pdf = muSplitPdfObject(input_pdf,pr[0],pr[1],result.cover_page)
                    if i in need_fix_cover_index:#if this book should be fix the cover
                        insert_blank_page = 1
                        if result.cover_page != -1:#if has a cover,append the blank to third page
                            insert_blank_page = 2
                        tmp_pdf = muInsertPagePdfObject(tmp_pdf,insert_blank_page)
                    muMakePrintablePdfFile(tmp_pdf,output_pdf,ride_ratio=result.ride_ratio)
                    